package cn.fboost.mtos.util;

import cn.fboost.mtos.entity.Config;
import cn.fboost.mtos.mapper.ConfigMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;

@Slf4j
@Component
public class ConfigUtil {
    private final ConfigMapper configMapper;

    public ConfigUtil(ConfigMapper configMapper) {
        this.configMapper = configMapper;
    }

    @Cacheable(cacheNames = "sys-config", key = "'all-config'", sync = true)
    public HashMap<String, Object> getAllConfig() {
        List<Config> data = configMapper.getAllConfig();

        HashMap<String, Object> result = new HashMap<>();
        data.forEach(config -> result.put(config.getK(), config.getV()));
        return result;
    }

    @Cacheable(cacheNames = "sys-config", key = "'prefix-' + #prefix", sync = true)
    public HashMap<String, Object> getPrefixConfig(String prefix) {
        List<Config> data = configMapper.getPrefixConfig(prefix);

        HashMap<String, Object> result = new HashMap<>();
        data.forEach(config -> result.put(config.getK(), config.getV()));
        return result;
    }

    @Cacheable(cacheNames = "sys-config", key = "#key", sync = true)
    public String getString(String key) {
        return configMapper.getConfig(key);
    }

    @Cacheable(cacheNames = "sys-config", key = "#key", sync = true)
    public int getInt(String key) {
        String intVal = configMapper.getConfig(key);
        if (intVal == null) {
            return 0;
        }

        return Integer.parseInt(intVal);
    }

    @Cacheable(cacheNames = "sys-config", key = "#key", sync = true)
    public double getDouble(String key) {
        String doubleVal = configMapper.getConfig(key);
        if (doubleVal == null) {
            return 0d;
        }

        return Double.parseDouble(doubleVal);
    }

    @CacheEvict(cacheNames = "sys-config", key = "'prefix-' + #prefix")
    public void clearPrefixConfig(String prefix) {
    }

    @CacheEvict(cacheNames = "sys-config", key = "#key")
    public void setConfig(String key, String value) {
        configMapper.setConfig(key, value);
    }
}
